<script setup lang="ts">
import dayjs from 'dayjs'
import { ref , nextTick} from 'vue'
import _ from 'lodash'
import { useUserStore } from '@/store/modules/user-store'
import { getLodop } from '@/lib/lodop/LodopFuncs'
import printModal from '@/components/business/print-modal/index.vue'
import { useEnums } from '@/hooks/plugins/useEnums'
import { returnOrderApi } from '@/api/business/storage/store-api'
import { INTO_STATUS_ENUM } from '@/constants/business/storage/inwarehouse/in-warehouse-const'
import { useTransformSpec } from '@/hooks/web/use-transform-spec'
const { getDescByValue } = useEnums()
const { transformSpec } = useTransformSpec()

const open = ref<boolean>(false)
const emit = defineEmits(['close', 'getList'])
const userStore = useUserStore()

const visible = ref(false)
// 详情
const options = ref([])
const batchData = ref([])
const printLog = ref({})
defineExpose({
  showDrawer
})
// 合并签收批次商品数据与入库单商品数据
function mergeGoodsData(detailGoods: any[], batchGoods: any[]): any[] {
  const list = new Map()
  // 构建以入库单商品数据为key的Map
  for (const item of detailGoods) {
    if (list.has(item.goods_id)) continue
    // 过滤条件-当前商品ID
    const filterConditions = { goods_id: item.goods_id }
    // 获取当前商品的所有规格信息-detailGoods[index].goods.spec
    const specs = _(detailGoods).find(filterConditions).goods.spec
    // 获取当前商品ID的所有入库单商品数量-num
    const num: number = _(detailGoods).filter(filterConditions).sumBy('base_num')
    // 获取当前商品ID的所有批次商品数据
    const batch = _(batchGoods).filter(filterConditions).value()
    // 获取当前商品ID的所有批次商品数量-initial_quantity
    const initial_quantity: number = _.sumBy(batch, 'initial_quantity')
    const value = {
      id: item.goods_id,
      goods_name: item.goods.goods_name,
      spec_name: item.spec.spec_name,
      unit_name: item.spec.unit_name,
      num: transformSpec(num, specs),
      initial_quantity: transformSpec(initial_quantity, specs),
      remark: item.remark,
      batch: batch.map((batchRow) => ({
        batch_time: dayjs(batchRow?.batch_time).format('YYYY-MM-DD'),
        initial_quantity: transformSpec(batchRow?.initial_quantity, specs),
        warehouse_name: `${batchRow?.warehouse?.name}(${getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', batchRow?.attribute_type)})`,
        location_code: batchRow?.warehouse_location?.code ?? ''
      })),
      sign_amount: _(batch)
        .map(({ sign_amount }) => Number(sign_amount))
        .sumBy()
        .toFixed(2)
    }
    list.set(item.goods_id, value)
  }
  return Array.from(list.values())
}
function showDrawer(item, detail) {
  options.value = item
  printLog.value = detail.printLog
  batchData.value = mergeGoodsData(detail.detail, detail.batch)
  visible.value = true
}
function onClose() {
  visible.value = false
}
const loading = ref(false)
const usePrint = () => {
  const onPrint = async () => {
    loading.value = true
try {
    const valData = await returnOrderApi.detail({ id: options.value.id, is_print: true })
    printLog.value = valData.data.printLog 
  } catch (error) {
    console.error('更新打印次数失败', error)
    loading.value = false
    return
  }

  await nextTick()

    const LODOP = getLodop()
    if (!LODOP) {
      open.value = true
      loading.value = false
      return
    }
    LODOP.PRINT_INITA('0mm', '0mm', '241mm', '93mm', '入库单')
    LODOP.SET_PRINT_PAGESIZE(1, '215.9mm', '93mm', '入库单')
    LODOP.ADD_PRINT_TABLE(20, '3%', '94%', '100%', document.querySelector('#printPurchase')?.outerHTML)
    
    LODOP.SET_PRINT_STYLEA(0, 'TableRowThickNess', '12pt')
    LODOP.ADD_PRINT_TEXT(30, '3%', 196, 20, '县链云仓')
    LODOP.SET_PRINT_STYLEA(0, 'ItemType', 0)
    LODOP.NewPageA()
    LODOP.PREVIEW()
    
    loading.value = false
  }
  return {
    onPrint
  }
}
const { onPrint } = usePrint()
function handleModalClose() {
  open.value = false
}
</script>

<template>
  <printModal :open="open" @cancel="handleModalClose" />
  <a-drawer title="入库单打印" :open="visible" @close="onClose">
    <template #closeIcon>
      <close @on-close="onClose" />
    </template>
    <table id="printPurchase" border="0" center cellSpacing="0" cellPadding="1" width="100%" style="border-collapse: collapse; font-size: 11pt">
      <tbody>
        <tr>
  <td colspan="8">
            <div style="line-height: 30px; text-align: center; font-size: 16pt; font-weight: 700">{{ userStore.getCompanyInfo.name }}入库单</div>
            <font style="position: absolute; right: 0; top: 0">
              <span tdata="pageNO" format="#">#</span>
              <span>/</span>
              <span tdata="pageCount" format="#">##</span>
            </font>
          </td>
  </tr>
        </tbody>
      <tbody>
        <tr>
          <td colspan="10">入库状态:{{ getDescByValue('STORE_STATUS_ENUM', Number(options.into_status)) }}&nbsp;&nbsp;&nbsp;&nbsp;单据日期:{{ options?.create_time }}&nbsp;&nbsp;&nbsp;&nbsp;任务编号:{{ options?.related.order_no ?? options?.related.no }}</td>
        </tr>
        <tr>
          <td colspan="10"
            ><span v-if="[INTO_STATUS_ENUM.PurchaseOrder.value, INTO_STATUS_ENUM.CompanyTransferOrder.value].includes(options.related_type)">
              <span v-if="options.related_type === INTO_STATUS_ENUM.PurchaseOrder.value">供应商:{{ options.related?.supplier?.name }}&nbsp;&nbsp;&nbsp;&nbsp;</span></span
            ><span v-if="options?.related?.customer?.name">司机/业务员:{{ options?.related?.customer?.name }}&nbsp;&nbsp;&nbsp;&nbsp;</span> 仓库:{{ options.related?.warehouse?.name || '-' }}- {{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', options.related?.warehouse?.attribute_type) }}&nbsp;&nbsp;&nbsp;&nbsp;打印次数:{{ printLog?.print_count || 0 }}&nbsp;&nbsp;&nbsp;&nbsp;打印时间:{{ dayjs().format('YYYY-MM-DD HH:mm:ss') }}</td
          >
        </tr>
        <tr>
          <td width="10%" style="border: 1pt solid #000">
            <div align="center"><b>序号</b></div>
          </td>
          <td width="30%" style="border: 1pt solid #000">
            <div align="center"><b>商品名称</b></div>
          </td>
          <td width="10%" style="border: 1pt solid #000">
            <div align="center"><b>规格</b></div>
          </td>
          <td width="10%" style="border: 1pt solid #000">
            <div align="center"><b>单位</b></div>
          </td>
          <td width="10%" style="border: 1pt solid #000">
            <div align="center"><b>订单数量</b></div>
          </td>
          <td width="10%" style="border: 1pt solid #000">
            <div align="center"><b>签收数量</b></div>
          </td>
          <td width="10%" style="border: 1pt solid #000">
            <div align="center"><b>小计</b></div>
          </td>
          <td width="10%" style="border: 1pt solid #000">
            <div align="center"><b>备注</b></div>
          </td>
        </tr>
        <tr v-for="(item, index) in batchData" :key="item.id">
          <td style="border: 1pt solid #000; text-align: center">{{ index + 1 }}</td>
          <td style="border: 1pt solid #000; text-align: center">{{ item.goods_name }}</td>
          <td style="border: 1pt solid #000; text-align: center">{{ item.spec_name }}</td>
          <td style="border: 1pt solid #000; text-align: center">{{ item.unit_name }}</td>
          <td style="border: 1pt solid #000; text-align: center">{{ item.num }}</td>
          <td style="border: 1pt solid #000; text-align: center">{{ item.initial_quantity == 0 ? '' : item.initial_quantity }}</td>
          <td style="border: 1pt solid #000; text-align: center">{{ item.sign_amount }}</td>
          <td style="border: 1pt solid #000; text-align: center">{{ item.remark }}</td>
        </tr>
        <tr>
          <td style="border: 1pt solid #000; text-align: center">总计</td>
          <td style="border: 1pt solid #000">&nbsp;</td>
          <td style="border: 1pt solid #000">&nbsp;</td>
          <td style="border: 1pt solid #000">&nbsp;</td>
          <td style="border: 1pt solid #000">&nbsp;</td>
          <td style="border: 1pt solid #000">&nbsp;</td>
          <td style="border: 1pt solid #000; text-align: center">{{ batchData.reduce((prev, item) => prev + Number(item.sign_amount), 0).toFixed(2) }}</td>
          <td style="border: 1pt solid #000">&nbsp;</td>
        </tr>
        <tr>
          <td style="font-weight: bold" colspan="3">备注:{{ options?.remark }}</td>
        </tr>
        <tr>
          <td colspan="3">仓管签字：</td>
          <td colspan="2">入库人签字：</td>
        </tr>
      </tbody>
    </table>
    <template #footer>
      <div class="flex justify-end">
        <a-button type="default" @click="onClose" style="margin-right: 8px">关闭</a-button>
        <a-button :loading="loading" type="primary" @click="onPrint">打印</a-button>
      </div>
    </template>
  </a-drawer>
</template>
